package com.example.smartgreenhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.smartgreenhouse.entity.FanOperationLog;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.mapper.FanOperationLogMapper;
import com.example.smartgreenhouse.mqtt.MqttMessageSender;
import com.example.smartgreenhouse.service.FanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class FanServiceImpl implements FanService {

    private final FanOperationLogMapper fanOperationLogMapper;
    private final MqttMessageSender mqttMessageSender;

    @Value("${mqtt.topic.fan_cmd}")
    private String topicFanCmd;

    @Value("${mqtt.topic.fan_auto_cmd}")
    private String topic_fan_auto_cmd;



    //cation == 1 开启自动控制
    //cation == 0 关闭自动控制
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> setFanAuto(Long fanId, Long greenhouseId, Long operatorId, Integer action) {
        try {
            mqttMessageSender.publish(topic_fan_auto_cmd, String.valueOf(action));
            log.info("已发送水泵控制指令: fanId={}, is_auto={}", fanId, action == 1);
        } catch (Exception e) {
            log.error("MQTT发布失败 | Topic: device/pump/{}/control | 错误: {}", fanId, e.getMessage());
            throw new RuntimeException("风扇控制指令发送失败，请检查MQTT连接配置", e); // 明确提示检查配置
//            log.error("水泵控制指令发送失败", e);
//            throw new RuntimeException("水泵控制指令发送失败");
        }
        Map<String,Object> operationLog = new HashMap<>();
        operationLog.put("code",200);
        operationLog.put("status","success");
        if(action==1){
            operationLog.put("message","风扇自动控制开启");
        }else{
            operationLog.put("message","风扇自动控制关闭");
        }
        operationLog.put("operationTime",LocalDateTime.now());
        return operationLog;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FanOperationLog controlFan(Long fanId, Long greenhouseId, String level, Long operatorId) {
        // 参数校验
        // 校验ENUM值
        if (!Arrays.asList("0", "1", "2", "3").contains(level)) {
            throw new BusinessException("档位必须是'0','1','2','3'");
        }

        // 发送控制指令
        sendControlCommand(fanId, level);

        // 记录操作日志
        return recordOperation(fanId, greenhouseId, level, operatorId);
    }

    @Override
    public List<FanOperationLog> getFanHistory(Long fanId) {
        return fanOperationLogMapper.selectList(
                new LambdaQueryWrapper<FanOperationLog>()
                        .eq(FanOperationLog::getFanId, fanId)
                        .orderByDesc(FanOperationLog::getOperateTime)
        );
    }



    private void sendControlCommand(Long fanId, String level) {
        try {
            mqttMessageSender.publish(topicFanCmd, String.valueOf(level));
            log.info("已发送风扇控制指令: fanId={}, level={}", fanId, level);
        } catch (Exception e) {
            log.error("MQTT发布失败 | Topic: {} | 错误: {}", topicFanCmd, e.getMessage());
            throw new RuntimeException("风扇控制指令发送失败，请检查MQTT连接配置", e);
        }
    }

    private FanOperationLog recordOperation(Long fanId, Long greenhouseId,
                                           String level, Long operatorId) {
        FanOperationLog log = new FanOperationLog();
        log.setFanId(fanId);
        log.setGreenhouseId(greenhouseId);
        log.setLevel(level);
        log.setOperatorId(operatorId);
        log.setOperateTime(LocalDateTime.now());

        fanOperationLogMapper.insert(log);
        return log;
    }
}